<template>
  <view>
    <!-- 企业认证会员展示发票类型选项；普通会员默认是普票抬头 -->
    <view v-if="isCertifyVip" class="list-bg">
      <SelectTabs
        :tabs-title="invoiceType.title"
        :tab-list="invoiceType.list"
        :current.sync="invoiceType.current"
      />
    </view>
    <view v-if="isNormalInvoice" class="list-bg">
      <SelectTabs
        :tabs-title="invoiceTitleType.title"
        :tab-list="invoiceTitleType.list"
        :current.sync="invoiceTitleType.current"
      />
    </view>
    <view class="list-bg">
      <InvoiceForm :form-items="formItems" :form-data.sync="formData" />
    </view>
    <!-- 底部按钮栏 -->
    <PageFooterBar
      only-btn
      :btn-list="btnList"
      @confirm="handleSave"
      @delete="handleDelete"
      @export="handleExportFromWX"
      @click="handleSave"
    />
  </view>
</template>
<script>
import PageFooterBar from '@/components/page-footer-bar'
// import InvoiceType from './components/InvoiceType'
import SelectTabs from './components/SelectTabs'
import InvoiceForm from './components/InvoiceForm'
import { saveOrUpdate, deleteInvoice } from '@/api/yc_invoice'
import { navigateBackPrePage } from '@/common/common'
export default {
  components: {
    PageFooterBar,
    SelectTabs,
    InvoiceForm
  },
  data() {
    return {
      btnList: [], // 底部栏集合
      invoiceIftId: '', // 发票id（只有编辑时有）
      formData: {}, // 发票表单数据
      defaultForm: {
        items: [
          { prop: 'invoiceTitle', label: '名称', placeholder: '请输入名称', maxlength: 32, required: true },
          {
            prop: 'taxId',
            label: '税号',
            placeholder: '请输入纳税人识别号',
            maxlength: 18,
            required: true
          },
          {
            prop: 'invoiceAddress',
            label: '注册地址',
            placeholder: '请输入单位注册地址信息',
            type: 'textarea',
            style: 'align-items: normal; line-height: normal;',
            leftStyle: 'margin-top: 15rpx;',
            maxlength: 48
          },
          { prop: 'tel', label: '注册电话', placeholder: '请输入注册电话号码', maxlength: 11, type: 'number' },
          { prop: 'accountBankC', label: '开户银行', placeholder: '请输入开户银行名称', maxlength: 32 },
          { prop: 'accountBankNo', label: '银行账户', placeholder: '请输入开户银行号码', maxlength: 20, type: 'number' },
          // { prop: 'priority', label: '设为默认', type: 'switch', rightStyle: 'width: auto;' },
        ],
        rules: {
          taxId: { reg: [/^[a-zA-Z0-9]+$/], msg: '请输入正确格式税号！只支持数字、字母' },
          tel: { reg: [/^[1][3,4,5,6,7,8,9][\d]{9}$/, /^((0\d{2,3}))?(-)?(\d{7,8})$/], msg: '请输入正确的电话号码' },
          accountBankNo: { reg: [/^\d+( \d+)*$/], msg: '银行卡号只能输入数字' }
        },
      },
      invoiceType: {
        title: '发票类型',
        current: 1,
        list: [
          { code: 1, label: '纸质普通发票' },
          { code: 0, label: '增值税专用发票' }
        ]
      },
      invoiceTitleType: {
        title: '发票抬头类型',
        current: 10,
        list: [
          { code: 10, label: '个人' },
          { code: 20, label: '单位' }
        ]
      }
    }
  },
  onLoad(options) {
    this.initConfigData(options)
  },
  computed: {
    // 是否是认证会员
    isCertifyVip() {
      const isCertify = this.vuex_memberCompanyInfo?.examStatus == 20 // 认证会员
      return isCertify
    },
    // 是否是crm公司（认证会员有此字段，普通会员没有）
    isCrmCompany() {
      const customerClassify = this.crmCustomerInfos?.customerClassify // 客户类型代码（10：公司；20：个人）
      const isCompany = customerClassify == 10
      return isCompany
    },
    // 是普票类型
    isNormalInvoice() {
      return this.invoiceType.current == 1
    },
    // 表单列集合
    formItems() {
      // crm客户类型（个人还是企业）如果是企业就只有单位抬头
      const isPersonTitle = this.invoiceTitleType.current == 10 // 个人抬头
      const isNormalPerson = !this.isCertifyVip && this.isNormalInvoice && isPersonTitle // 个人普通会员-个人抬头
      const isCertifyPerson = this.isCertifyVip && this.isNormalInvoice && isPersonTitle // 企业认证会员-个人抬头
      const isCertifySpecial = this.isCertifyVip && !this.isNormalInvoice // 企业认证会员 - 专票抬头
      if (isNormalPerson || isCertifyPerson) { // 发票抬头类型为个人时，只展示第一项名称
        const firstItem = [...this.defaultForm.items].shift()
        return [firstItem]
      }
      if (this.isCrmCompany) { // 账号为crm企业类型时，名称和税号不可编辑
        return [...this.defaultForm.items].map(item => {
          const disabledItems = ['invoiceTitle', 'taxId']
          if (disabledItems.includes(item.prop)) return { ...item, required: true, disabled: true }
          return { ...item, required: !this.isNormalInvoice } // 发票类型为专票全部必填
        })
      }
      if (isCertifySpecial) { // 发票类型为专票时，全部必填
        return [...this.defaultForm.items].map(item => ({ ...item, required: true }))
      }
      return [...this.defaultForm.items] // 其余情况默认表单items
    },
    // crm用户信息
    crmCustomerInfos() {
      if (Array.isArray(this.vuex_crmCustomerInfos)) {
        return this.vuex_crmCustomerInfos[0]
      }
      return this.vuex_crmCustomerInfos
    }
  },
  methods: {
    // 初始化配置数据
    initConfigData(options) {
      const { type, invoiceDetail } = options
      this.updateNavigationTitle(type)
      this.setBtnList(type)
      let formData = {}
      if (invoiceDetail) {
        formData = JSON.parse(invoiceDetail)
        this.invoiceIftId = formData.invoiceIftId
        this.invoiceType.current = formData.invoiceType
        this.invoiceTitleType.current = formData.taxId ? 20 : 10
      }
      if (this.isCrmCompany) {
        // 账号为crm企业类型时，编辑不修改名称、税号，新增取全局crm数据进行默认赋值
        formData.invoiceTitle = formData.invoiceTitle ? formData.invoiceTitle : this.crmCustomerInfos.crmCustomerName
        formData.taxId = formData.taxId ? formData.taxId : this.crmCustomerInfos.businessLicenseNum
        // crm公司类型 - 发票抬头只展示单位
        this.invoiceTitleType.list = this.invoiceTitleType.list.filter(item => item.code == 20)
        this.invoiceTitleType.current = 20
      }
      this.setFormData(formData)
    },
    // 设置表单数据
    setFormData(invoiceDetail = {}) {
      this.formData = this.formItems.reduce((value, item) => {
        value[item.prop] = invoiceDetail[item.prop] ?? null
        return value
      }, {})
    },
    // 更新navigation栏标题
    updateNavigationTitle(type) {
      const typeMapsTitle = {
        'add': '新增发票抬头',
        'edit': '编辑发票抬头'
      }
      const title = typeMapsTitle[type] ?? '发票抬头'
      uni.setNavigationBarTitle({ title })
    },
    // 设置底部栏按钮集合
    setBtnList(type) {
      const addBar = [
        // #ifdef MP-WEIXIN
        {
          name: '从微信导入',
          backgroundColor: '#0BB955',
          color: '#FFFFFF',
          emit: 'export',
          width: 334,
          src: '/static/image/icon_wechat@2x.png'
        },
        // #endif
        {
          name: '保存',
          isLinearBg: true,
          // #ifdef MP-WEIXIN
          width: 334
          // #endif
        },
      ]
      const editBar = [
        { name: '删除', width: 334, emit: 'delete' },
        { name: '保存', isLinearBg: true, width: 334 }
      ]
      const typeMapsBar = {
        'add': addBar,
        'edit': editBar
      }
      this.btnList = typeMapsBar[type] ?? []
    },
    // 获取保存时的入参
    getSaveParams() {
      const formData = this.formItems.reduce((value, item) => {
        value[item.prop] = this.formData[item.prop]
        return value
      }, {})
      return {
        ...formData,
        memberId: this.vuex_memberInfo.memberId,
        customerCode: this.crmCustomerInfos?.customerCode,
        invoiceType: this.invoiceType.current,
        id: this.invoiceIftId
      }
    },
    // 保存
    async handleSave() {
      const validateResult = this.validateFormItems()
      if (!validateResult) return
      const params = this.getSaveParams()
      const res = await saveOrUpdate(params)
      if (res.code == 0) {
        this.$u.toast('保存成功')
        setTimeout(() => {
          // uni.navigateBack({ delta: 1 })
          navigateBackPrePage({ updateTimeStamp: Date.now() })
        }, 1000)
      } else {
        this.$u.toast(res.msg)
      }
    },
    // 表单校验
    validateFormItems() {
      const formItems = [...this.formItems]
      // 非空校验
      const hasNull = formItems.some(item => {
        if (item.required && !this.formData[item.prop]) {
          this.$u.toast(`${item.label}不能为空！`)
          return true
        }
        return false
      })
      if (hasNull) return false
      // 条件校验
      const isPattern = formItems.some(item => {
        if (!this.defaultForm.rules[item.prop] || !this.formData[item.prop]) return false // 没有校验规则或者非必填项为空值不进行判断
        const { reg, msg } = this.defaultForm.rules[item.prop] ?? {}
        const execFailed = reg.every(pattern => !pattern.test(this.formData[item.prop]))
        if (execFailed) {
          this.$u.toast(msg)
          return true
        }
        return false
      })
      if (isPattern) return false
      return true
    },
    // 获取保存时所需的发票类型值
    getSaveInvoiceType() {
      if (!this.isCertifyUser) return '' // 非认证用户，保存时传空
      if (this.invoiceType == 10) return 1 // 普票传1
      if (this.invoiceType == 20) return 0 // 专票传0
    },
    // 删除
    async handleDelete() {
      const params = { id: this.invoiceIftId }
      const res = await deleteInvoice(params)
      if (res.code == 0) {
        this.$u.toast('删除成功')
        setTimeout(() => {
          // uni.navigateBack({ delta: 1 })
          navigateBackPrePage({ updateTimeStamp: Date.now() })
        }, 1000)
      } else {
        this.$u.toast(res.msg)
      }
    },
    // 从微信导入
    handleExportFromWX() {
      const that = this
      uni.authorize({
        scope: 'scope.invoiceTitle',
        success() {
          uni.chooseInvoiceTitle({
            success(res) {
              const invoiceDetail = {
                invoiceTitle: res.title,
                taxId: res.taxNumber,
                invoiceAddress: res.companyAddress,
                tel: res.telephone.replace(/\-/, ''),
                accountBankC: res.bankName,
                accountBankNo: res.bankAccount
              }
              if (that.isCrmCompany) { // 账号为crm企业类型时，导入不修改名称、税号
                invoiceDetail.invoiceTitle = that.formData.invoiceTitle
                invoiceDetail.taxId = that.formData.taxId
              }
              that.setFormData(invoiceDetail)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
